package top.pcat.util;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import top.pcat.config.RedisConfig;

public class RedisPoolUtil {
    public static volatile JedisPool jedisPool = null;

    /**
     * 创建单例的RedisPool
     *
     * @param redisConfig 参数
     */
    public RedisPoolUtil(RedisConfig redisConfig) {
        if (null == jedisPool) {
            synchronized (RedisPoolUtil.class) {
                if (null == jedisPool) {
                    GenericObjectPoolConfig<Jedis> poolConfig = new GenericObjectPoolConfig<>();
                    poolConfig.setMaxTotal(redisConfig.getJedisPoolMaxTotal());
                    poolConfig.setMaxIdle(redisConfig.getJedisPoolMaxIdle());
                    poolConfig.setTestOnBorrow(redisConfig.getJedisPoolTestOnBorrow());
                    jedisPool = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout(), redisConfig.getPassword());
                }
            }
        }
    }

    /**
     * 获取jedis
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 获取jedis线程池
     */
    public static JedisPool getRedisPoolUtil() {
        return jedisPool;
    }

    ;

    /**
     * 关闭jedis线程池
     */
    public static void close() {
        if (jedisPool != null) jedisPool.close();
    }

}
